<?php

namespace App\Service\playlet;
use App\Model\Playlet;
use App\Model\WeCom;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;

class WeComService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }


    const STATUS_ENABLE  = 1;


    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;
        $status      = $params['status'] ?? '';

        $query = WeCom::query()->select(['id','name','cover','status','created_at','updated_at']);

        if ($keyword) {
            $query->orWhere([['name', 'like', '%'.$keyword.'%']]);
        }
        if ($status != '') {
            $query->where(['status' => $status]);
        }
        $models = $query->orderBy('id','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            $data['status_name']  = self::$commonStatus[$item->status];
            $selectData[] =$data;

        }
        $data = $models->toArray();
        $data['data'] = $selectData;
        return $data;
    }

    public function createOrUpdate(Array $postData,$is_update=false,WeCom $weComInfo = null){
        $name = $postData['name'];
        $cover = $postData['cover'];
        $status = $postData['status'];
        $model = !empty($weComInfo)? $weComInfo : new WeCom();
        $model->name = $name;
        $model->cover = $cover;
        $model->status = $status;
        if($model->save()){

            if($is_update){
                //查找短剧有没有绑定企业微信，有的话更新图片
                Playlet::query()->where(['we_com_id' => $model->id])->update(['we_com_cover' => $cover]);
            }
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
        }
    }
}